from rest_framework.viewsets import ViewSet

from users.models import User, UserCart, UserCartDone, UserPinglun
from rest_framework.generics import CreateAPIView,ListAPIView
from .serializers import UserModelSerializer, UserCartModelSerializer, UserCartDoneModelSerializer, \
    UserPinglunModelSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from django_redis import get_redis_connection
from zhenghanshu2.utils import constant
import logging
import random
from zhenghanshu2.utils.tencent.sms import send_sms_single
from django.shortcuts import HttpResponse
from django.conf import settings

log = logging.getLogger("django")


class CheckMobileAPIView(APIView):
    def get(self, request, mobile):
        try:
            User.objects.get(mobile=mobile)
            result = False
            message = "手机号码已经被注册！"
            code = status.HTTP_400_BAD_REQUEST
        except User.DoesNotExist:
            result = True
            message = "手机号没有被注册"
            code = status.HTTP_200_OK
        return Response({"result": result, "message": message}, status=code)


class SMSAPIView(APIView):
    def get(self, request, mobile):

        # 接收手机号码以后，验证是否已经注册
        try:
            User.objects.get(mobile=mobile)
            return Response("当前手机号已经被注册！", status=status.HTTP_400_BAD_REQUEST)
        except:
            pass

        try:
            # 引入redis,选择redis里的某个数据库
            redis = get_redis_connection("sms_code")

            # 判断当前手机号码是否曾经在60s发送短信
            mobile_inerval = redis.get("mobile_%s" % mobile)
            if mobile_inerval:
                return Response({"result": "对不起，手机短信发送间隔不足一分钟"}, status=status.HTTP_400_BAD_REQUEST)

            # 在以后开发中如果一次性要写入多条redis命令，建议采用管道操作【事务操作】来把多条数据整理成 一块，一并发送给redis
            pip = redis.pipeline()
            pip.multi()

            # 设置短信间隔时间
            pip.setex("mobile_%s" % mobile, constant.SMS_INTERVAL_TIME, "_")  # “_”表示占位符，没有任何意义
            # 生成短信号码并把短信和手机号码保存到redis中
            code = "%06d" % random.randint(0, 999999)
            print(code)
            # 可以使用string格式进行数据保存
            # setex 13405265712 300 666666
            pip.setex("sms_%s" % mobile, constant.SMS_EXPIRE_TIME, code)
            # 执行管道中的所有命令
            pip.execute()

            template_id = settings.TENCENT_SMS_TEMPLATE.get("register")
            # res = send_sms_single(mobile, template_id, [code, ])
            # if res['result'] != 0:
            #     return Response({"result": "短信发送失败！"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        except:
            log.error("发送错误信息！")
            return Response({"result": "服务器存储有误！"}, status=status.HTTP_507_INSUFFICIENT_STORAGE)
        return Response({"result": "短信发送成功"}, status=status.HTTP_200_OK)


class UserAPIView(CreateAPIView):
    """用户注册"""
    queryset = User.objects.all()
    serializer_class = UserModelSerializer


class UserCartAPIView(CreateAPIView):
    """用户的购物车"""
    queryset = UserCart.objects.all()
    serializer_class = UserCartModelSerializer


class UserCartDeleteAPIView(ViewSet):
    def del_cart(self,request):
        """从购物车中删除商品"""
        id = request.query_params.get("id")
        print(id)
        try:
            UserCart.objects.filter(id=id).update(is_delete=True)
        except UserCart.DoesNotExist:
            return Response({"message":"参数有误"},status=status.HTTP_400_BAD_REQUEST)

        return Response({"message":"删除商品成功"})



class UserCartDoneAPIView(CreateAPIView):
    """用户的购物车"""
    queryset = UserCartDone.objects.all()
    serializer_class = UserCartDoneModelSerializer


class UserPinglunAPIView(CreateAPIView):
    """用户的购物车"""
    queryset = UserPinglun.objects.all()
    serializer_class = UserPinglunModelSerializer
